package com.ndp.fb.mq.consumer.business.syncbusiness;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ndp.fb.constant.CommonConstants;
import com.ndp.fb.fbagent.service.AdImageFBService;
import com.ndp.fb.model.AdResourceStats;
import com.ndp.fb.model.business.bo.consumer.BusinessParams;
import com.ndp.fb.model.business.bo.consumer.FacebookResult;
import com.ndp.fb.model.business.bo.nfs.NfsConfig;
import com.ndp.fb.model.fbagent.param.adimage.AdImageParam;
import com.ndp.fb.model.fbagent.result.adgroup.FbAdgroup;
import com.ndp.fb.model.fbagent.result.adimage.FbAdImage;
import com.ndp.fb.mongo.api.AccountAdImageMongoService;
import com.ndp.fb.mongo.api.AdImageMongoService;
import com.ndp.fb.mongo.api.AdResourceStatsMongoService;
import com.ndp.fb.mongo.model.AccountAdImageMongo;
import com.ndp.fb.mongo.model.Image;
import com.ndp.fb.rdb.api.AdCreativeRdbService;
import com.ndp.fb.rdb.api.EntrustAccountRdbService;
import com.ndp.fb.redis.api.RedisClient;
import com.ndp.fb.util.ImageUtil;
import com.ndp.fb.util.NFSUtil;
import com.restfb.DefaultJsonMapper;
import com.restfb.JsonMapper;
import com.restfb.json.JsonArray;
import com.restfb.json.JsonObject;
import com.restfb.util.UrlUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by infi on 2015/3/12.
 */
@Component
public class SyncAdImageBusiness extends AbstractSyncBusiness {
    private final Logger logger = LoggerFactory.getLogger(SyncAdImageBusiness.class);

    @Reference
    private AdImageFBService adImageFBService;
    @Autowired
    private RedisClient redisClient;
    @Reference
    private AdCreativeRdbService adCreativeRdbService;
    @Reference
    private AccountAdImageMongoService accountAdImageMongoService;

    @Reference
    private AdImageMongoService adImageMongoService;
    @Reference
    private AdResourceStatsMongoService adResourceStatsMongoService;

    @Reference
    private EntrustAccountRdbService entrustAccountRdbService;

    @Autowired
    private NFSUtil nfsUtil;
    @Autowired
    private NfsConfig nfsConfig;

    @Override
    protected void saveCache(BusinessParams businessParams, FacebookResult facebookResult, JsonObject jsonObject) {
        //发送消息请求处理每页500条数据
        //从缓存中取看是否存在
        //查询数据库
        JsonArray jsonSummary = jsonObject.getJsonArray("data");
        logger.info("-----AdImage业务数据 " + businessParams.getAccountId() + " 账号下本次拉取回来数量：" + jsonSummary.length());
        Long lastUpdatedTime = (Long) this.redisClient.get(CommonConstants.SYNC_BUSINESS_AD_IMAGE_UPDATEDTIME + businessParams.getAccountId());
        if (lastUpdatedTime == null) {
            businessParams.setLastUpdatedTime(0L);
            lastUpdatedTime = 0L;
        }
        //flag代表是否还需要取下一页
        if (jsonObject.has("paging")) {
            JsonObject pageJsonObject = jsonObject.getJsonObject("paging");
            if (!pageJsonObject.has("previous")) {
                businessParams.setIsFirstPage(1);
            }
        }
        if (businessParams.getIsFirstPage() == 1) {
            businessParams.setLastUpdatedTime(lastUpdatedTime);
        }
        boolean flag = consumerAdImage(jsonObject, businessParams);
        //flag代表是否还需要取下一页
        if (flag && jsonObject.has("paging")) {
            JsonObject pageJsonObject = jsonObject.getJsonObject("paging");
            if (pageJsonObject.has("next")) {
                facebookResult.setHasNextPage(true);
                Map<String, List<String>> paramsMap = UrlUtils.extractParametersFromUrl(pageJsonObject.getString("next"));
                facebookResult.setAfter(getVal(paramsMap, "after"));
            }
        }
        facebookResult.setDataList(null);
        facebookResult.setHasError(false);
    }
    private boolean consumerAdImage(JsonObject jsonObject, BusinessParams businessParams) {
        Boolean isNextPage = true;
        JsonMapper jsonMapper=new DefaultJsonMapper();
        List<FbAdImage> fbAdImages = jsonMapper.toJavaList(jsonObject.toString(), FbAdImage.class);
        if(CollectionUtils.isNotEmpty(fbAdImages)){
            logger.info("本次拉下来的adimage有"+fbAdImages.size()+"条");
            List<AccountAdImageMongo> accountImages = new ArrayList<>();
            AccountAdImageMongo accountAdImageMongo = null;
            for(FbAdImage fbAdImage:fbAdImages){
                accountAdImageMongo = new AccountAdImageMongo();
                accountAdImageMongo.setMongodbId(fbAdImage.getId());
                BeanUtils.copyProperties(fbAdImage, accountAdImageMongo);
                accountImages.add(accountAdImageMongo);
            }
            accountAdImageMongoService.batchSaveOrUpdateAccountAdImage(accountImages);
        }else{
            logger.info("本次拉下来的adimage有0条");
        }
        return isNextPage;
    }
    
    @Override
    protected BusinessParams buildBusinessParams(String body, Map<String, String> equipmentMap) {
        String accountId = equipmentMap.get("entrustAccountId");
        String token = equipmentMap.get("accessToken");
        BusinessParams businessParams = new BusinessParams();
        businessParams.setAccountId(Long.parseLong(accountId));
        businessParams.setToken(token);
        businessParams.setBusinessClass(FbAdgroup.class);
        businessParams.setBusinessCacheFlag(CommonConstants.SYNC_BUSINESS_AD_IMAGE_FLAG + accountId);
        businessParams.setLastUpdatedTime(Long.valueOf(equipmentMap.get("lastupdatedtime").equals("null") ? "0" : equipmentMap.get("lastupdatedtime")));
        return businessParams;
    }

    @Override
    protected void nextPage(BusinessParams businessParams, String after) {
        AdImageParam adImageParam = new AdImageParam();
        adImageParam.setAccessToken(businessParams.getToken());
        adImageParam.setFbAccountId(businessParams.getAccountId());
        adImageParam.setAfter(after);
        adImageParam.setLastUpdatedTime(businessParams.getLastUpdatedTime());
        adImageFBService.getAdImages(adImageParam);
    }

    public void getImageHashCallback(String body, Map<String, String> equipmentMap) {
        try {
            if (StringUtils.isEmpty(body)) {
                logger.warn("get image_hash facebook返回为空!");
            } else {
                Map fbAdimage = this.getFBAdimage(body);
                String hash = (String) fbAdimage.get("hash");
                String type = equipmentMap.getOrDefault("type", "1");
                if (StringUtils.isEmpty(hash)) {
                    logger.warn("facebook hash返回为空:type>> {}!",type);
                    logger.warn("body >>>>" + body);
                    if(type.equals("2")){
                        Image image = new Image();
                        String md5 = equipmentMap.get("md5");
                        String picture = equipmentMap.get("picture");
                        String url = "";
                        image.setMd5(md5);
                        image.setPicture(picture);
                        image.setHash("-1");
                        image.setUrl(url);
                        image.setResult(body);
                        adImageMongoService.upsertAdImage(image);
                    }
                } else{
                    if(type.equals("1")){
                        String mongodbId = equipmentMap.get("mongodbId");
                        adResourceStatsMongoService.updateHashbyMongodbId(mongodbId, hash);
                        AdResourceStats adResourceStats = adResourceStatsMongoService.findByMongodbId(mongodbId);
                        Image image = new Image();
                        image.setCreated_time(System.currentTimeMillis());
                        image.setMd5(adResourceStats.getMd5());
                        image.setHash(hash);
                        image.setPicture(adResourceStats.getVisitPath());
                        image.setUrl(adResourceStats.getVisitPath());
                        adImageMongoService.upsertAdImage(image);
                    }else if(type.equals("2")){
                        Image image = new Image();
                        String md5 = equipmentMap.get("md5");
                        String picture = equipmentMap.get("picture");
                        String url = "";
                        if(StringUtils.isBlank(md5)){
                            md5 = ImageUtil.getImageMd5(picture);
                        }
                        if(picture.indexOf(nfsConfig.getDomain())>-1){
                            url = picture;
                        }else{
                            url = nfsConfig.getFullAddress() + CommonConstants.SYMBOL_SLASH + nfsUtil.uploadToNFS(url, false);
                        }
                        image.setMd5(md5);
                        image.setPicture(picture);
                        image.setHash(hash);
                        image.setUrl(url);
                        adImageMongoService.upsertAdImage(image);
                    }

                }
            }
        } catch (Exception e) {
            logger.error("syncAdImageCallback error >>>", e);
        }
    }


    /**
     * 解析facebook返回,得到url和hash数据
     *
     * @param result
     * @return
     */
    private Map getFBAdimage(String result) {
        Map imageMap = new HashMap();
        try {
            JSONObject jsonObject = JSON.parseObject(result);
            Map map = (Map) jsonObject.get("images");
            if (map == null) {
                logger.warn("facebook返回没有images字段!");
                return imageMap;
            }
            Set set = map.entrySet();
            for (Iterator it = set.iterator(); it.hasNext(); ) {
                Map.Entry entry = (Map.Entry) it.next();
                JSONObject j1 = JSON.parseObject(entry.getValue().toString());
                String hash = j1.getString("hash");
                if (StringUtils.isNotEmpty(hash)) {
                    imageMap.put("hash", hash);
                } else {
                    logger.warn("facebook返回没有 hash 字段!");
                }
                String url = j1.getString("url");
                if (StringUtils.isNotEmpty(url)) {
                    imageMap.put("url", url);
                } else {
                    logger.warn("facebook返回没有 url 字段!");
                }
            }
        } catch (Exception e) {
            logger.error("解析facebook返回错误!");
            logger.error(e.getMessage(), e);
        }
        return imageMap;
    }

}
